<?php

namespace common\behavior\CommonMessagePushing;


use common\model\UserModel;
use common\service\BehaviorService;
use common\service\OrderService;
use common\service\ProjectStepCategoryConfirmConfigService;
use common\service\ReviewRequestMessageService;
use Webman\Stomp\Client;

/**
 * 创建订单需审核 消息通知
 */
class OrderNeedReviewBehavior
{
    /**
     * @param $params
     * @return void
     */
    public function run($params)
    {
        /***********  预处理开始  ************/
        $params = BehaviorService::getInstance()->dealParam(
            $params,
            [
                'order_data_list' => '',
            ],
            [
                'order_data_list' => [],
            ],
            'data',
            ['type' => 'create_order'],
        );
        /***********  行为判断  ************/
        if ($params === false) {
            return;
        }
        /***********  变量迁移  ************/
        list($orderDataList) = $params;
        if (empty($orderDataList)) {
            return;
        }
        /***********  预处理结束  ************/

        /***********  原逻辑迁移  ************/
        $orders = array_column($orderDataList, 'order');
        $toTenantIdData = array_column($orders, 'to_tenant_id', 'to_tenant_id');
        $toTenantData = teamones_request('teamones-im', 'tenant/select', [
            'param' => [
                'filter' => [
                    'tenant.id' => ["-in", implode(',', $toTenantIdData)]
                ]
            ]
        ])['data'];
        $toTenantMap = array_column($toTenantData['rows'], null, 'id');
        $userIdData = array_column($orders, 'created_by', 'created_by');
        $reviewers = [];
        foreach ($orderDataList as $orderData) {
            $order = $orderData['order'];
            foreach ($orderData['review_data']['reviewers'] as $reviewer) {
                if ($reviewer['skip'] || $reviewer['user_id'] <= 0) {
                    continue;
                }
                $reviewers[$order['id']][$reviewer['user_id']] = $reviewer['user_id'];
                $userIdData[$reviewer['user_id']] = $reviewer['user_id'];
            }
        }
        $userData = model(UserModel::class)->where(['id' => ['IN', implode(',', $userIdData)]])->field("id,name,union_id")->select();
        $userMap = array_column($userData, null, 'id');
        $notifyMessages = [];
        foreach ($orders as $order) {
            $messageParam = [
                'first' => '有任务需要外包',
                'creator_name' => $userMap[$order['created_by']]['name'] ?? "",
                'order_name' => $order['name'],
                'supplier_name' => $toTenantMap[$order['to_tenant_id']]['name'] ?? "",
                'create_at' => date("Y/m/d H:i", $order['created']),
                'remark' => '请及时处理',
                'order_type' => $order['type'],
                'tenant_id' => $order['from_tenant_id'],
                'project_id' => $order['project_id'],
                'order_id' => $order['id'],
            ];

            //检查是否需要通知
            if (!isset($reviewers[$order['id']]) || count($reviewers[$order['id']]) == 0) {
                continue;
            }

            foreach ($reviewers[$order['id']] as $reviewer) {
                $notifyMessages[] = [
                    'param' => $messageParam,
                    'receiver_id' => $userMap[$reviewer]['union_id'],
                ];
            }
        }

        if (empty($notifyMessages)) {
            return;
        }
        $messageTemplateId = OrderService::getInstance()->getOrderReviewNotifyTemplateId();
        $messageGenerated = [];
        foreach ($notifyMessages as $notifyMessage) {
            $messageGenerated[] = [
                "param" => $notifyMessage['param'],
                'receiver' => $notifyMessage['receiver_id'],
                'template_id' => $messageTemplateId,
                'content_type' => 'card_message',
                'notice_type' => 'message_review',
                'message_key' => 'order_need_review',
            ];
        }

        /***********  发送新的队列  ************/
        foreach ($messageGenerated as $message) {
            Client::send('common_message_pushing', build_queue_data_with_xu([
                'message_generated' => [$message],
            ]));
        }
        /***********  结束  ************/
    }
}
